package services

import (
	"context"
	"navidog/backend/storage"
	"navidog/backend/types"
)

type ConnectionService struct {
	ctx   context.Context
	store *storage.ConnectionStorage
}

func NewConnectionService() *ConnectionService {
	store := storage.NewConnectionStorage()
	return &ConnectionService{store: store}
}

func (c *ConnectionService) StartUp(ctx context.Context) {
	c.ctx = ctx
}

func (c *ConnectionService) CreateConnection(connection types.Connection) types.JSResp {
	connection.CatUuid()

	configs, err := c.store.Load()
	if err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	(*configs)[connection.Uuid] = connection
	if err := c.store.Save(configs); err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	return types.JSResp{
		Success: true,
		Msg:     "连接创建成功",
		Data:    nil,
	}
}

func (c *ConnectionService) ListConnections() types.JSResp {
	configs, err := c.store.Load()
	if err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	connections := make([]types.Connection, 0, len(*configs))
	for _, conn := range *configs {
		connections = append(connections, conn)
	}
	return types.JSResp{
		Success: true,
		Msg:     "获取连接配置成功",
		Data:    connections,
	}
}

func (c *ConnectionService) getConnection(uuid string) (types.Connection, error) {
	configs, err := c.store.Load()
	if err != nil {
		return types.Connection{}, err
	}
	return (*configs)[uuid], nil
}

func (c *ConnectionService) GetConnection(uuid string) types.JSResp {
	connection, err := c.getConnection(uuid)
	if err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	return types.JSResp{
		Success: true,
		Msg:     "获取连接配置成功",
		Data:    connection,
	}
}

func (c *ConnectionService) DeleteConnection(uuid string) types.JSResp {
	configs, err := c.store.Load()
	if err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	if _, ok := (*configs)[uuid]; !ok {
		return types.JSResp{
			Success: false,
			Msg:     "连接不存在",
		}
	}
	delete(*configs, uuid)
	if err := c.store.Save(configs); err != nil {
		return types.JSResp{
			Success: false,
			Msg:     err.Error(),
		}
	}
	return types.JSResp{
		Success: true,
		Msg:     "连接删除成功",
		Data:    nil,
	}
}
